import React, { useState, useEffect } from 'react';
import { 
  Table, 
  Input, 
  Button, 
  Modal, 
  Form, 
  Select, 
  message, 
  Space, 
  Tag, 
  Card, 
  Row, 
  Col, 
  Checkbox,
  Divider,
  Tooltip,
  Progress,
  Statistic,
  Drawer,
  List,
  Badge
} from 'antd';
import { 
  PlusOutlined, 
  SearchOutlined, 
  FilterOutlined, 
  StarOutlined, 
  StarFilled,
  SaveOutlined,
  EyeOutlined,
  BarChartOutlined,
  DollarOutlined,
  RiseOutlined,
  FallOutlined
} from '@ant-design/icons';

const { Option } = Select;
const { Search } = Input;

const FundList = () => {
  const [funds, setFunds] = useState([]);
  const [filteredFunds, setFilteredFunds] = useState([]);
  const [loading, setLoading] = useState(false);
  const [searchText, setSearchText] = useState('');
  const [selectedFunds, setSelectedFunds] = useState([]);
  const [isFilterDrawerVisible, setIsFilterDrawerVisible] = useState(false);
  const [isPortfolioModalVisible, setIsPortfolioModalVisible] = useState(false);
  const [savedPortfolios, setSavedPortfolios] = useState([]);
  const [filterForm] = Form.useForm();
  const [portfolioForm] = Form.useForm();

  // 筛选选项状态
  const [fundTypes, setFundTypes] = useState([]);
  const [fundCategories, setFundCategories] = useState([]);
  const [riskLevels, setRiskLevels] = useState([]);
  const [companies, setCompanies] = useState([]);

  // API基础URL
  const API_BASE_URL = 'http://localhost:5000/api';

  // 获取基金列表
  const fetchFunds = async (params = {}) => {
    setLoading(true);
    try {
      const queryParams = new URLSearchParams({
        page: 1,
        limit: 100,
        ...params
      });

      console.log('正在获取基金列表...', `${API_BASE_URL}/funds?${queryParams}`);

      const response = await fetch(`${API_BASE_URL}/funds?${queryParams}`, {
        headers: {
          'Content-Type': 'application/json'
        }
      });

      if (!response.ok) {
        throw new Error(`获取基金列表失败: ${response.status} ${response.statusText}`);
      }

      const data = await response.json();
      console.log('获取基金列表成功:', data);
      setFunds(data.data || []);
      setFilteredFunds(data.data || []);
    } catch (error) {
      console.error('获取基金列表错误:', error);
      
      // 如果API调用失败，使用更多mock数据
      const defaultFunds = [
        {
          id: 1,
          code: '000001',
          name: '华夏成长混合',
          fund_type: '混合型',
          category: '成长型',
          manager_name: '张坤',
          company_name: '华夏基金',
          establishment_date: '2001-12-18',
          total_assets: 125.6,
          nav: 2.856,
          daily_return: 1.25,
          weekly_return: 3.45,
          monthly_return: 8.92,
          yearly_return: 15.67,
          max_drawdown: -12.34,
          sharpe_ratio: 1.23,
          tags: JSON.stringify(['成长型', '混合型', '消费行业', '价值投资']),
          risk_level: '中高风险',
          min_investment: 1000,
          management_fee: 1.5,
          custodian_fee: 0.25,
          subscription_fee: 1.2,
          redemption_fee: 0.5,
          benchmark: '沪深300指数',
          description: '专注于成长型股票投资，追求长期资本增值'
        },
        {
          id: 2,
          code: '110022',
          name: '易方达消费行业股票',
          fund_type: '股票型',
          category: '行业主题',
          manager_name: '萧楠',
          company_name: '易方达基金',
          establishment_date: '2010-08-20',
          total_assets: 98.3,
          nav: 3.245,
          daily_return: -0.85,
          weekly_return: 2.18,
          monthly_return: 6.34,
          yearly_return: 18.92,
          max_drawdown: -15.67,
          sharpe_ratio: 1.45,
          tags: JSON.stringify(['消费行业', '股票型', '主题投资', '白酒']),
          risk_level: '高风险',
          min_investment: 1000,
          management_fee: 1.5,
          custodian_fee: 0.25,
          subscription_fee: 1.5,
          redemption_fee: 0.5,
          benchmark: '中证消费指数',
          description: '专注于消费行业投资，重点配置白酒、家电等消费龙头'
        },
        {
          id: 3,
          code: '161039',
          name: '富国中证新能源汽车',
          fund_type: '指数型',
          category: '行业指数',
          manager_name: '李元博',
          company_name: '富国基金',
          establishment_date: '2015-06-11',
          total_assets: 80.2,
          nav: 1.876,
          daily_return: 0.65,
          weekly_return: 1.12,
          monthly_return: 4.23,
          yearly_return: 12.34,
          max_drawdown: -10.12,
          sharpe_ratio: 1.10,
          tags: JSON.stringify(['新能源', '指数型', '成长型']),
          risk_level: '中风险',
          min_investment: 1000,
          management_fee: 1.0,
          custodian_fee: 0.20,
          subscription_fee: 1.0,
          redemption_fee: 0.5,
          benchmark: '中证新能源汽车指数',
          description: '紧跟新能源行业发展，布局未来产业龙头'
        },
        {
          id: 4,
          code: '000216',
          name: '华安安信消费服务',
          fund_type: '混合型',
          category: '消费型',
          manager_name: '胡宜斌',
          company_name: '华安基金',
          establishment_date: '2013-03-28',
          total_assets: 60.5,
          nav: 2.123,
          daily_return: 0.32,
          weekly_return: 1.05,
          monthly_return: 3.12,
          yearly_return: 10.56,
          max_drawdown: -8.90,
          sharpe_ratio: 1.18,
          tags: JSON.stringify(['消费型', '混合型', '稳健']),
          risk_level: '中低风险',
          min_investment: 1000,
          management_fee: 1.2,
          custodian_fee: 0.22,
          subscription_fee: 1.1,
          redemption_fee: 0.5,
          benchmark: '中证消费服务指数',
          description: '消费服务行业优选，稳健增值'
        },
        {
          id: 5,
          code: '003123',
          name: '中欧医疗健康混合',
          fund_type: '混合型',
          category: '医疗健康',
          manager_name: '葛兰',
          company_name: '中欧基金',
          establishment_date: '2016-09-28',
          total_assets: 150.8,
          nav: 4.321,
          daily_return: 1.05,
          weekly_return: 2.56,
          monthly_return: 7.89,
          yearly_return: 20.12,
          max_drawdown: -13.45,
          sharpe_ratio: 1.35,
          tags: JSON.stringify(['医疗健康', '成长型', '混合型']),
          risk_level: '高风险',
          min_investment: 1000,
          management_fee: 1.5,
          custodian_fee: 0.25,
          subscription_fee: 1.3,
          redemption_fee: 0.5,
          benchmark: '中证医疗指数',
          description: '专注医疗健康行业，成长空间大'
        },
        {
          id: 6,
          code: '510300',
          name: '华泰柏瑞沪深300ETF',
          fund_type: 'ETF',
          category: '宽基指数',
          manager_name: '柳军',
          company_name: '华泰柏瑞基金',
          establishment_date: '2012-05-28',
          total_assets: 200.0,
          nav: 3.001,
          daily_return: 0.15,
          weekly_return: 0.98,
          monthly_return: 2.45,
          yearly_return: 8.76,
          max_drawdown: -7.80,
          sharpe_ratio: 1.05,
          tags: JSON.stringify(['ETF', '宽基', '指数型']),
          risk_level: '中低风险',
          min_investment: 100,
          management_fee: 0.5,
          custodian_fee: 0.10,
          subscription_fee: 0.8,
          redemption_fee: 0.3,
          benchmark: '沪深300指数',
          description: '宽基指数ETF，分散投资风险'
        },
        {
          id: 7,
          code: '000478',
          name: '建信稳定增利债券',
          fund_type: '债券型',
          category: '纯债型',
          manager_name: '李博',
          company_name: '建信基金',
          establishment_date: '2011-11-11',
          total_assets: 50.3,
          nav: 1.789,
          daily_return: 0.05,
          weekly_return: 0.22,
          monthly_return: 0.98,
          yearly_return: 4.56,
          max_drawdown: -2.34,
          sharpe_ratio: 0.95,
          tags: JSON.stringify(['债券型', '稳健', '低风险']),
          risk_level: '低风险',
          min_investment: 1000,
          management_fee: 0.8,
          custodian_fee: 0.15,
          subscription_fee: 0.5,
          redemption_fee: 0.2,
          benchmark: '中证全债指数',
          description: '纯债投资，追求稳定收益'
        },
        {
          id: 8,
          code: '001102',
          name: '南方新兴消费股票',
          fund_type: '股票型',
          category: '消费型',
          manager_name: '茅炜',
          company_name: '南方基金',
          establishment_date: '2014-07-18',
          total_assets: 70.6,
          nav: 2.654,
          daily_return: 0.75,
          weekly_return: 1.45,
          monthly_return: 5.12,
          yearly_return: 13.45,
          max_drawdown: -9.87,
          sharpe_ratio: 1.12,
          tags: JSON.stringify(['消费型', '股票型', '成长型']),
          risk_level: '中风险',
          min_investment: 1000,
          management_fee: 1.3,
          custodian_fee: 0.22,
          subscription_fee: 1.1,
          redemption_fee: 0.5,
          benchmark: '中证消费指数',
          description: '新兴消费行业投资，成长动力强'
        },
        {
          id: 9,
          code: '002190',
          name: '农银汇理新能源主题',
          fund_type: '股票型',
          category: '新能源',
          manager_name: '赵诣',
          company_name: '农银汇理基金',
          establishment_date: '2015-12-09',
          total_assets: 90.1,
          nav: 3.012,
          daily_return: 1.12,
          weekly_return: 2.78,
          monthly_return: 7.34,
          yearly_return: 16.78,
          max_drawdown: -11.23,
          sharpe_ratio: 1.28,
          tags: JSON.stringify(['新能源', '成长型', '股票型']),
          risk_level: '中高风险',
          min_investment: 1000,
          management_fee: 1.6,
          custodian_fee: 0.26,
          subscription_fee: 1.4,
          redemption_fee: 0.5,
          benchmark: '中证新能源指数',
          description: '新能源主题投资，紧跟行业趋势'
        },
        {
          id: 10,
          code: '519674',
          name: '银河创新成长混合',
          fund_type: '混合型',
          category: '创新成长',
          manager_name: '王群航',
          company_name: '银河基金',
          establishment_date: '2017-03-15',
          total_assets: 55.7,
          nav: 2.345,
          daily_return: 0.92,
          weekly_return: 2.01,
          monthly_return: 6.78,
          yearly_return: 14.56,
          max_drawdown: -10.56,
          sharpe_ratio: 1.20,
          tags: JSON.stringify(['创新', '成长型', '混合型']),
          risk_level: '中风险',
          min_investment: 1000,
          management_fee: 1.4,
          custodian_fee: 0.23,
          subscription_fee: 1.2,
          redemption_fee: 0.5,
          benchmark: '中证创新成长指数',
          description: '创新成长主题，追求长期资本增值'
        }
      ];
      setFunds(defaultFunds);
      setFilteredFunds(defaultFunds);
    } finally {
      setLoading(false);
    }
  };

  // 获取筛选选项
  const fetchFilterOptions = async () => {
    try {
      console.log('正在获取筛选选项...');

      const response = await fetch(`${API_BASE_URL}/funds/filter/options`, {
        headers: {
          'Content-Type': 'application/json'
        }
      });

      if (!response.ok) {
        throw new Error(`获取筛选选项失败: ${response.status} ${response.statusText}`);
      }

      const data = await response.json();
      console.log('获取筛选选项成功:', data);
      setFundTypes(data.fundTypes || []);
      setFundCategories(data.categories || []);
      setRiskLevels(data.riskLevels || []);
      setCompanies(data.companies || []);
    } catch (error) {
      console.error('获取筛选选项错误:', error);
      
      // 如果API调用失败，使用默认选项
      setFundTypes(['股票型', '混合型', '债券型', '指数型', '货币型', 'QDII']);
      setFundCategories(['成长型', '价值型', '平衡型', '行业主题', '个股', '行业指数']);
      setRiskLevels(['低风险', '中低风险', '中风险', '中高风险', '高风险']);
      setCompanies(['华夏基金', '易方达基金', '嘉实基金', '招商基金', '中欧基金', '汇添富基金']);
    }
  };

  // 获取基金统计信息
  const fetchFundStats = async (params = {}) => {
    try {
      const queryParams = new URLSearchParams(params);
      const response = await fetch(`${API_BASE_URL}/funds/stats?${queryParams}`, {
        headers: {
          'Content-Type': 'application/json'
        }
      });

      if (!response.ok) {
        throw new Error('获取统计信息失败');
      }

      return await response.json();
    } catch (error) {
      console.error('获取统计信息错误:', error);
      return null;
    }
  };

  // 获取基金详情
  const fetchFundDetail = async (fundId) => {
    try {
      console.log('正在获取基金详情...', fundId);
      const response = await fetch(`${API_BASE_URL}/funds/${fundId}`, {
        headers: {
          'Content-Type': 'application/json'
        }
      });
      if (!response.ok) {
        throw new Error(`获取基金详情失败: ${response.status} ${response.statusText}`);
      }
      const data = await response.json();
      console.log('获取基金详情成功:', data);
      return data.fund; // 返回基金详情
    } catch (error) {
      console.error('获取基金详情错误:', error);
      // mock数据兜底
      return {
        id: fundId,
        code: '000001',
        name: '华夏成长混合',
        fund_type: '混合型',
        category: '成长型',
        manager_name: '张坤',
        company_name: '华夏基金',
        establishment_date: '2001-12-18',
        total_assets: 125.6,
        nav: 2.856,
        daily_return: 1.25,
        yearly_return: 15.67,
        max_drawdown: -12.34,
        sharpe_ratio: 1.23,
        tags: ['成长型', '混合型', '消费行业', '价值投资'],
        risk_level: '中高风险',
        min_investment: 1000,
        management_fee: 1.5,
        custodian_fee: 0.25,
        subscription_fee: 1.2,
        redemption_fee: 0.5,
        benchmark: '沪深300指数',
        description: '专注于成长型股票投资，追求长期资本增值'
      };
    }
  };

  // 获取基金画像
  const fetchFundProfile = async (fundId) => {
    try {
      console.log('正在获取基金画像...', fundId);
      const response = await fetch(`${API_BASE_URL}/funds/${fundId}/profile`, {
        headers: {
          'Content-Type': 'application/json'
        }
      });
      if (!response.ok) {
        throw new Error(`获取基金画像失败: ${response.status} ${response.statusText}`);
      }
      const data = await response.json();
      console.log('获取基金画像成功:', data);
      return data;
    } catch (error) {
      console.error('获取基金画像错误:', error);
      // mock数据兜底
      return {
        fundId,
        style: '成长型',
        risk: '中高风险',
        industry: '消费',
        region: '中国',
        description: 'mock画像：专注于成长型消费行业投资',
      };
    }
  };

  // 保存基金组合
  const savePortfolio = async (portfolioData) => {
    try {
      console.log('正在保存基金组合...', portfolioData);

      const response = await fetch(`${API_BASE_URL}/funds/portfolio`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(portfolioData)
      });

      if (!response.ok) {
        throw new Error(`保存组合失败: ${response.status} ${response.statusText}`);
      }

      const result = await response.json();
      console.log('保存基金组合成功:', result);
      return result;
    } catch (error) {
      console.error('保存组合错误:', error);
      return null;
    }
  };

  // 获取用户组合列表
  const fetchUserPortfolios = async () => {
    try {
      console.log('正在获取用户组合列表...');
      const response = await fetch(`${API_BASE_URL}/funds/portfolio/user`, {
        headers: {
          'Content-Type': 'application/json'
        }
      });
      if (!response.ok) {
        throw new Error(`获取组合列表失败: ${response.status} ${response.statusText}`);
      }
      const data = await response.json();
      console.log('获取用户组合列表成功:', data);
      setSavedPortfolios(data.data || []);
    } catch (error) {
      console.error('获取组合列表错误:', error);
      // mock数据兜底，增加多组组合
      setSavedPortfolios([
        {
          id: 1,
          name: '我的消费精选组合',
          funds: [
            { code: '000001', name: '华夏成长混合', weight: 60 },
            { code: '110022', name: '易方达消费行业股票', weight: 40 }
          ],
          createTime: '2024-01-01',
          description: '专注消费行业，精选优质成长基金',
        },
        {
          id: 2,
          name: '科技成长组合',
          funds: [
            { code: '003123', name: '中欧医疗健康混合', weight: 50 },
            { code: '161039', name: '富国中证新能源汽车', weight: 50 }
          ],
          createTime: '2024-02-15',
          description: '聚焦科技与医疗，成长潜力大',
        },
        {
          id: 3,
          name: '稳健收益组合',
          funds: [
            { code: '110011', name: '易方达中小盘混合', weight: 70 },
            { code: '000216', name: '华安安信消费服务', weight: 30 }
          ],
          createTime: '2024-03-10',
          description: '适合风险偏好低、追求稳健收益的投资者',
        }
      ]);
    }
  };

  // 初始化数据
  useEffect(() => {
    fetchFunds();
    fetchFilterOptions();
    fetchUserPortfolios();
  }, []);

  const columns = [
    {
      title: '选择',
      key: 'selection',
      width: 60,
      render: (_, record) => (
        <Checkbox
          checked={selectedFunds.some(fund => fund.id === record.id)}
          onChange={(e) => handleFundSelection(record, e.target.checked)}
        />
      ),
    },
    {
      title: '基金代码',
      dataIndex: 'code',
      key: 'code',
      width: 100,
      render: (code) => <span style={{ fontWeight: 'bold', color: '#1890ff' }}>{code}</span>,
    },
    {
      title: '基金名称',
      dataIndex: 'name',
      key: 'name',
      width: 200,
      render: (name, record) => (
        <div>
          <div style={{ fontWeight: 'bold' }}>{name}</div>
          <div style={{ fontSize: '12px', color: '#666' }}>{record.fund_type} | {record.category}</div>
        </div>
      ),
    },
    {
      title: '基金经理',
      dataIndex: 'manager_name',
      key: 'manager_name',
      width: 100,
    },
    {
      title: '基金公司',
      dataIndex: 'company_name',
      key: 'company_name',
      width: 120,
    },
    {
      title: '净值',
      dataIndex: 'nav',
      key: 'nav',
      width: 100,
      render: (value) => {
        const navValue = parseFloat(value);
        const displayValue = isNaN(navValue) ? 0 : navValue;
        return <span style={{ fontWeight: 'bold' }}>{displayValue}</span>;
      },
    },
    {
      title: '日涨跌幅',
      dataIndex: 'daily_return',
      key: 'daily_return',
      width: 100,
      render: (return_) => {
        const returnValue = parseFloat(return_);
        const displayValue = isNaN(returnValue) ? 0 : returnValue;
        return (
          <span style={{ 
            color: displayValue > 0 ? '#52c41a' : displayValue < 0 ? '#f5222d' : '#666',
            fontWeight: 'bold'
          }}>
            {displayValue > 0 ? '+' : ''}{displayValue}%
          </span>
        );
      },
    },
    {
      title: '年化收益',
      dataIndex: 'yearly_return',
      key: 'yearly_return',
      width: 100,
      render: (return_) => {
        const returnValue = parseFloat(return_);
        const displayValue = isNaN(returnValue) ? 0 : returnValue;
        return (
          <span style={{ 
            color: displayValue > 0 ? '#52c41a' : displayValue < 0 ? '#f5222d' : '#666',
            fontWeight: 'bold'
          }}>
            {displayValue > 0 ? '+' : ''}{displayValue}%
          </span>
        );
      },
    },
    {
      title: '规模(亿)',
      dataIndex: 'total_assets',
      key: 'total_assets',
      width: 100,
      render: (assets) => {
        const assetsValue = parseFloat(assets);
        const displayValue = isNaN(assetsValue) ? 0 : assetsValue;
        return <span style={{ fontWeight: 'bold' }}>{displayValue}</span>;
      },
    },
    {
      title: '风险等级',
      dataIndex: 'risk_level',
      key: 'risk_level',
      width: 100,
      render: (level) => {
        const colors = {
          '低风险': 'green',
          '中低风险': 'blue',
          '中风险': 'orange',
          '中高风险': 'red',
          '高风险': 'volcano'
        };
        return <Tag color={colors[level]}>{level}</Tag>;
      },
    },
    {
      title: '标签',
      dataIndex: 'tags',
      key: 'tags',
      width: 200,
      render: (tags) => {
        const tagArray = typeof tags === 'string' ? JSON.parse(tags || '[]') : tags || [];
        return (
        <div>
            {tagArray.slice(0, 2).map(tag => (
            <Tag color="blue" key={tag} style={{ marginBottom: '4px' }}>
              {tag}
            </Tag>
          ))}
            {tagArray.length > 2 && (
              <Tag color="default">+{tagArray.length - 2}</Tag>
          )}
        </div>
        );
      },
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      render: (_, record) => (
        <Space size="small">
          <Tooltip title="查看详情">
            <Button 
              type="link" 
              size="small"
              icon={<EyeOutlined />}
              onClick={() => handleViewDetail(record)}
            />
          </Tooltip>
          <Tooltip title="查看画像">
            <Button 
              type="link" 
              size="small"
              icon={<BarChartOutlined />}
              onClick={() => handleViewProfile(record)}
            />
          </Tooltip>
        </Space>
      ),
    },
  ];

  const handleFundSelection = (fund, checked) => {
    if (checked) {
      setSelectedFunds([...selectedFunds, fund]);
    } else {
      setSelectedFunds(selectedFunds.filter(f => f.id !== fund.id));
    }
  };

  const handleSearch = (value) => {
    setSearchText(value);
    fetchFunds({ search: value });
  };

  const handleFilter = async () => {
    try {
      const values = await filterForm.validateFields();
      const params = {};
      
      if (values.fundType?.length > 0) params.fundType = values.fundType.join(',');
      if (values.category?.length > 0) params.category = values.category.join(',');
      if (values.riskLevel?.length > 0) params.riskLevel = values.riskLevel.join(',');
      if (values.company?.length > 0) params.company = values.company.join(',');
      if (values.minReturn !== undefined && values.minReturn !== '') params.minReturn = values.minReturn;
      if (values.maxReturn !== undefined && values.maxReturn !== '') params.maxReturn = values.maxReturn;
      if (values.minAssets !== undefined && values.minAssets !== '') params.minAssets = values.minAssets;
      if (values.maxAssets !== undefined && values.maxAssets !== '') params.maxAssets = values.maxAssets;

      await fetchFunds(params);
      setIsFilterDrawerVisible(false);
      message.success('筛选条件已应用');
    } catch (error) {
      console.error('筛选表单验证失败:', error);
    }
  };

  const handleSavePortfolio = async () => {
    if (selectedFunds.length === 0) {
      message.warning('请先选择基金');
      return;
    }

    try {
      const values = await portfolioForm.validateFields();
      const portfolioData = {
        name: values.name,
        description: values.description,
        funds: selectedFunds.map(fund => ({ id: fund.id }))
      };

      const result = await savePortfolio(portfolioData);
      if (result) {
        setSelectedFunds([]);
      setIsPortfolioModalVisible(false);
      portfolioForm.resetFields();
      message.success('基金组合保存成功');
        fetchUserPortfolios(); // 重新获取组合列表
      }
    } catch (error) {
      console.error('组合表单验证失败:', error);
    }
  };

  const handleViewDetail = async (fund) => {
    const fundDetail = await fetchFundDetail(fund.id);
    if (fundDetail) {
    Modal.info({
      title: `${fund.name} - 基金详情`,
      width: 800,
      content: (
        <div>
          <Row gutter={16}>
            <Col span={12}>
              <Card size="small" title="基本信息">
                <p><strong>基金代码：</strong>{fund.code}</p>
                  <p><strong>基金类型：</strong>{fund.fund_type}</p>
                <p><strong>基金分类：</strong>{fund.category}</p>
                  <p><strong>基金经理：</strong>{fund.manager_name}</p>
                  <p><strong>基金公司：</strong>{fund.company_name}</p>
                  <p><strong>成立时间：</strong>{fund.establishment_date}</p>
                  <p><strong>风险等级：</strong>{fund.risk_level}</p>
              </Card>
            </Col>
            <Col span={12}>
              <Card size="small" title="收益表现">
                  <p><strong>最新净值：</strong>{fund.nav}</p>
                <p><strong>日涨跌幅：</strong>
                    <span style={{ color: fund.daily_return > 0 ? '#52c41a' : '#f5222d' }}>
                      {fund.daily_return > 0 ? '+' : ''}{fund.daily_return}%
                  </span>
                </p>
                <p><strong>周涨跌幅：</strong>
                    <span style={{ color: fund.weekly_return > 0 ? '#52c41a' : '#f5222d' }}>
                      {fund.weekly_return > 0 ? '+' : ''}{fund.weekly_return}%
                  </span>
                </p>
                <p><strong>月涨跌幅：</strong>
                    <span style={{ color: fund.monthly_return > 0 ? '#52c41a' : '#f5222d' }}>
                      {fund.monthly_return > 0 ? '+' : ''}{fund.monthly_return}%
                  </span>
                </p>
                <p><strong>年化收益：</strong>
                    <span style={{ color: fund.yearly_return > 0 ? '#52c41a' : '#f5222d' }}>
                      {fund.yearly_return > 0 ? '+' : ''}{fund.yearly_return}%
                  </span>
                </p>
              </Card>
            </Col>
          </Row>
          <Row gutter={16} style={{ marginTop: '16px' }}>
            <Col span={12}>
              <Card size="small" title="费用信息">
                  <p><strong>管理费率：</strong>{fund.management_fee}%</p>
                  <p><strong>托管费率：</strong>{fund.custodian_fee}%</p>
                  <p><strong>认购费率：</strong>{fund.subscription_fee}%</p>
                  <p><strong>赎回费率：</strong>{fund.redemption_fee}%</p>
                  <p><strong>最低投资：</strong>{fund.min_investment}元</p>
              </Card>
            </Col>
            <Col span={12}>
              <Card size="small" title="投资信息">
                  <p><strong>基金规模：</strong>{fund.total_assets}亿元</p>
                  <p><strong>最大回撤：</strong>{fund.max_drawdown}%</p>
                  <p><strong>夏普比率：</strong>{fund.sharpe_ratio}</p>
                <p><strong>业绩基准：</strong>{fund.benchmark}</p>
                  <p><strong>投资风格：</strong>{typeof fund.tags === 'string' ? JSON.parse(fund.tags || '[]').join(', ') : (fund.tags || []).join(', ')}</p>
              </Card>
            </Col>
          </Row>
          <Card size="small" title="基金描述" style={{ marginTop: '16px' }}>
            <p>{fund.description}</p>
          </Card>
        </div>
      ),
    });
    }
  };

  const handleViewProfile = async (fund) => {
    const fundProfile = await fetchFundProfile(fund.id);
    if (fundProfile) {
    Modal.info({
      title: `${fund.name} - 基金画像`,
      width: 600,
      content: (
        <div>
          <Row gutter={16}>
            <Col span={12}>
                <Statistic title="年化收益率" value={fundProfile.yearly_return} suffix="%" />
            </Col>
            <Col span={12}>
                <Statistic title="最大回撤" value={fundProfile.max_drawdown} suffix="%" />
            </Col>
          </Row>
          <Divider />
          <div>
              <p><strong>夏普比率：</strong>{fundProfile.sharpe_ratio}</p>
              <p><strong>投资风格：</strong>{typeof fundProfile.tags === 'string' ? JSON.parse(fundProfile.tags || '[]').join(', ') : (fundProfile.tags || []).join(', ')}</p>
              <p><strong>风险等级：</strong>{fundProfile.risk_level}</p>
              <p><strong>适合投资者：</strong>{fundProfile.suitableInvestor}</p>
              <p><strong>表现评级：</strong>{fundProfile.performanceRating}</p>
          </div>
        </div>
      ),
    });
    }
  };

  const handleSelectAll = (checked) => {
    if (checked) {
      setSelectedFunds(filteredFunds);
    } else {
      setSelectedFunds([]);
    }
  };

  const handleClearSelection = () => {
    setSelectedFunds([]);
  };

  return (
    <div style={{ padding: '24px' }}>
      {/* 统计信息 */}
      <Row gutter={16} style={{ marginBottom: '24px' }}>
        <Col span={6}>
          <Card>
            <Statistic 
              title="总基金数" 
              value={filteredFunds.length} 
              prefix={<DollarOutlined />} 
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic 
              title="已选择" 
              value={selectedFunds.length} 
              prefix={<StarOutlined />} 
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic 
              title="平均年化收益" 
              value={(() => {
                if (filteredFunds.length === 0) return 0;
                const validReturns = filteredFunds
                  .map(fund => {
                    const returnValue = parseFloat(fund.yearly_return);
                    return isNaN(returnValue) ? 0 : returnValue;
                  })
                  .filter(returnValue => returnValue !== 0);
                
                if (validReturns.length === 0) return 0;
                const average = validReturns.reduce((sum, val) => sum + val, 0) / validReturns.length;
                return average.toFixed(2);
              })()} 
              suffix="%" 
              prefix={<RiseOutlined />}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic 
              title="平均最大回撤" 
              value={(() => {
                if (filteredFunds.length === 0) return 0;
                const validDrawdowns = filteredFunds
                  .map(fund => {
                    const drawdownValue = parseFloat(fund.max_drawdown);
                    return isNaN(drawdownValue) ? 0 : Math.abs(drawdownValue);
                  })
                  .filter(drawdownValue => drawdownValue !== 0);
                
                if (validDrawdowns.length === 0) return 0;
                const average = validDrawdowns.reduce((sum, val) => sum + val, 0) / validDrawdowns.length;
                return average.toFixed(2);
              })()} 
              suffix="%" 
              prefix={<FallOutlined />}
              valueStyle={{ color: '#f5222d' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 搜索和操作栏 */}
      <div style={{ marginBottom: '16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div style={{ display: 'flex', gap: '16px', alignItems: 'center' }}>
          <Search
            placeholder="输入基金代码/名称/经理/公司/标签"
            style={{ width: 400 }}
            onSearch={handleSearch}
            onChange={(e) => setSearchText(e.target.value)}
          />
          <Button 
            icon={<FilterOutlined />}
            onClick={() => setIsFilterDrawerVisible(true)}
          >
            高级筛选
          </Button>
        </div>
        <div style={{ display: 'flex', gap: '8px' }}>
          <Button 
            onClick={handleSelectAll}
            disabled={filteredFunds.length === 0}
          >
            全选
          </Button>
          <Button 
            onClick={handleClearSelection}
            disabled={selectedFunds.length === 0}
          >
            清空选择
          </Button>
          <Button 
            type="primary" 
            icon={<SaveOutlined />}
            onClick={() => setIsPortfolioModalVisible(true)}
            disabled={selectedFunds.length === 0}
          >
            保存组合 ({selectedFunds.length})
          </Button>
        </div>
      </div>

      {/* 基金列表 */}
      <Table 
        dataSource={filteredFunds} 
        columns={columns} 
        rowKey="id"
        loading={loading}
        pagination={{
          total: filteredFunds.length,
          pageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
        }}
        scroll={{ x: 1500 }}
      />

      {/* 高级筛选抽屉 */}
      <Drawer
        title="高级筛选"
        placement="right"
        width={400}
        open={isFilterDrawerVisible}
        onClose={() => setIsFilterDrawerVisible(false)}
        footer={
          <div style={{ textAlign: 'right' }}>
            <Button onClick={() => setIsFilterDrawerVisible(false)} style={{ marginRight: 8 }}>
              取消
            </Button>
            <Button onClick={() => {
              filterForm.resetFields();
              fetchFunds();
              setIsFilterDrawerVisible(false);
            }} style={{ marginRight: 8 }}>
              重置
            </Button>
            <Button type="primary" onClick={handleFilter}>
              应用筛选
            </Button>
          </div>
        }
      >
        <Form form={filterForm} layout="vertical">
          <Form.Item name="fundType" label="基金类型">
            <Select mode="multiple" placeholder="选择基金类型">
              {fundTypes.map(type => (
                <Option key={type} value={type}>{type}</Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item name="category" label="基金分类">
            <Select mode="multiple" placeholder="选择基金分类">
              {fundCategories.map(category => (
                <Option key={category} value={category}>{category}</Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item name="riskLevel" label="风险等级">
            <Select mode="multiple" placeholder="选择风险等级">
              {riskLevels.map(level => (
                <Option key={level} value={level}>{level}</Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item name="company" label="基金公司">
            <Select mode="multiple" placeholder="选择基金公司">
              {companies.map(company => (
                <Option key={company} value={company}>{company}</Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item name="minReturn" label="最小年化收益(%)">
            <Input type="number" placeholder="输入最小收益率" />
          </Form.Item>

          <Form.Item name="maxReturn" label="最大年化收益(%)">
            <Input type="number" placeholder="输入最大收益率" />
          </Form.Item>

          <Form.Item name="minAssets" label="最小规模(亿元)">
            <Input type="number" placeholder="输入最小规模" />
          </Form.Item>

          <Form.Item name="maxAssets" label="最大规模(亿元)">
            <Input type="number" placeholder="输入最大规模" />
          </Form.Item>
        </Form>
      </Drawer>

      {/* 保存组合模态框 */}
      <Modal
        title="保存基金组合"
        open={isPortfolioModalVisible}
        onOk={handleSavePortfolio}
        onCancel={() => setIsPortfolioModalVisible(false)}
        width={600}
      >
        <Form form={portfolioForm} layout="vertical">
          <Form.Item
            name="name"
            label="组合名称"
            rules={[{ required: true, message: '请输入组合名称' }]}
          >
            <Input placeholder="请输入组合名称" />
          </Form.Item>

          <Form.Item
            name="description"
            label="组合描述"
          >
            <Input.TextArea 
              placeholder="请输入组合描述" 
              rows={3}
            />
          </Form.Item>

          <div style={{ marginTop: '16px' }}>
            <h4>已选择的基金 ({selectedFunds.length}只)</h4>
            <List
              size="small"
              dataSource={selectedFunds}
              renderItem={fund => (
                <List.Item>
                  <List.Item.Meta
                    title={`${fund.name} (${fund.code})`}
                    description={`${fund.manager_name} | ${fund.company_name} | 年化收益: ${(() => {
                      const returnValue = parseFloat(fund.yearly_return);
                      return isNaN(returnValue) ? 0 : returnValue;
                    })()}%`}
                  />
                </List.Item>
              )}
            />
          </div>
        </Form>
      </Modal>
    </div>
  );
};

export default FundList; 